<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\ServiceCostEnum;
use app\model\CrontabTaskModel;
use app\model\TaskAccountCompareModel;
use app\service\cost\flow\FlowInterface;
use app\service\cost\TaskAccountService;
use app\service\CrontabTaskService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class MediaCostCompareWork extends BaseWork implements DailyStatWork
{
    public const REDIS_TASK_KEY = ServiceCostEnum::CACHE_CONFIG['media_cost_compare_list'];

    public ?string $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('media_cost_compare_work');
        // 设置参数
        $this->setDescription('回溯数据结果处理脚本')
            ->addArgument('date', Argument::OPTIONAL, '日期 Ymd')
            ->setHelp('php think media_cost_compare_work');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $st = time() + 5 * 60;
        $redis = Cache::store('redis')->handler();
        $output->writeln('=======回溯数据结果处理开始' . date('Y-m-d H:i:s', time()) . '=======');
        try {
            while (time() < $st) {
                $id = $redis->lPop(self::REDIS_TASK_KEY);
                $model = (new TaskAccountCompareModel())->find($id);
                if ($model instanceof TaskAccountCompareModel && $model->getKey()) {
                    $this->setTag($id . '-' . $model->getAttr('type'));
                    $service = TaskAccountService::getCostFlowService(intval($model->getAttr('type')));
                    if (! $service instanceof FlowInterface) {
                        $output->writeln('服务类型未知' . date('Y-m-d H:i:s', time()));
                        continue;
                    }
                    $res = $service->pullCompareData($model);
                    if (! $res) {
                        $output->writeln('回溯失败,任务id：' . $model->getKey() . $service::getError(0) . date('Y-m-d H:i:s', time()));
                    }
                    if ($model->getAttr('type') == 1) {
                        // 昨日更新任务执行时间
                        CrontabTaskService::setSingleTask($this);
                    }
                }
            }
        } catch (\Exception $e) {
            $output->writeln($e->getMessage() . date('Y-m-d H:i:s', time()));
        }
        $output->writeln('=======回溯数据结果处理结束' . date('Y-m-d H:i:s', time()) . '=======');
    }
}
